<template>
  <el-select v-model="selectedValue" :placeholder="placeholder" clearable filterable remote :remote-method="handleRemote" :loading="loading" popper-class="scroll-select-popper" style="width: 100%" @visible-change="handleVisibleChange">
    <!-- 下拉选项 -->
    <el-option v-for="item in options" :key="item[valueKey]" :label="item.productSpecificationName" :value="item.productSpecificationName" />
    <!-- 加载提示 -->
  </el-select>
</template>
<script>
export default {
  name: 'ScrollSelect',
  props: {
    value: { type: [String, Number, Array], required: true },
    placeholder: { type: String, default: '请输入关键词搜索' },
    multiple: { type: Boolean, default: false },
    // 必须传入一个返回 Promise 的函数，用于远程请求
    remoteMethod: { type: Function, required: true },
    labelKey: { type: String, default: 'name' },
    valueKey: { type: String, default: 'id' }
  },
  data() {
    return {
      selectedValue: this.value,
      options: [], // 所有选项
      loading: false, // 加载动画
      busy: false, // 是否正在请求
      hasMore: true, // 是否还有更多数据
      queryFrom: {
        pageNum: 1,
        pageSize: 20,
        commonSearch: ''
      }
    };
  },
  watch: {
    value(val) {
      this.selectedValue = val;
    },
    selectedValue(val) {
      this.$emit('input', val);
    }
  },
  mounted() {
    this.$nextTick(() => {
      const dropdown = document.querySelector('.scroll-select-popper .el-select-dropdown__wrap');
      if (dropdown) {
        dropdown.addEventListener('scroll', this.handleScroll);
      }
    });
  },
  beforeDestroy() {
    const dropdown = document.querySelector('.scroll-select-popper .el-select-dropdown__wrap');
    if (dropdown) {
      dropdown.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    handleRemote(query) {
      this.queryFrom.commonSearch = query;
      this.queryFrom.pageNum = 1; // 回到第一页
      this.hasMore = true;
      // 如果搜索内容为空，则不清空原有数据
      // 否则清空现有数据并重新加载匹配项
      this.options = [];
      this.fetchData();
    },
    /**
     * 获取数据的方法（支持分页）
     */
    async fetchData() {
      if (this.busy || !this.hasMore) {
        return;
      }
      this.loading = true;
      this.busy = true;
      try {
        const res = await this.remoteMethod({
          ...this.queryFrom
        });
        if (res.data && res.data.length > 0) {
          // 第一次加载或搜索时直接赋值；否则追加
          if (this.queryFrom.pageNum === 1 && this.queryFrom.commonSearch.trim() !== '') {
            this.options = [...res.data];
          } else {
            this.options = [...this.options, ...res.data]; // 不清空已有数据
          }
          // 判断是否还有更多
          this.hasMore = true;
          this.queryFrom.pageNum++;
        } else {
          this.hasMore = false;
        }
      } catch (e) {
        console.error('请求失败：', e);
        this.hasMore = false;
      } finally {
        this.loading = false;
        this.busy = false;
      }
    },
    handleVisibleChange(visible) {
      if (visible && this.options.length === 0) {
        this.fetchData(); // 首次打开下拉框加载数据
      }
    },
    handleScroll(event) {
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      if (scrollHeight - scrollTop <= clientHeight + 50 && !this.busy && this.hasMore) {
        this.fetchData(); // 加载更多数据
      }
    }
  }
};
</script>
<style scoped>
.loading-more {
  text-align: center;
  padding: 8px;
  font-size: 12px;
  color: #999;
}
</style>
